#ifndef TSB_CONTROLLER_CONFIGURATION
#define TSB_CONTROLLER_CONFIGURATION
/*
* 
* @license	Apache License 2.0
* @author	Eugene Kuznetsov
*
*/
#include "Base.hpp"
#include "CDataStorage.hpp"
#include <string>

#define CONFIGURATION_DATABASE_FILE "config.db"
#define SQL_CREATE_TABLE_DEVICES "CREATE TABLE IF NOT EXISTS main.devices"\
	"(id INTEGER NOT NULL PRIMARY KEY, type_id INTEGER NOT NULL, "\
	"server_1 INTEGER, server_2 INTEGER, server_3 INTEGER)"
#define SQL_CREATE_TABLE_SERVERS "CREATE TABLE IF NOT EXISTS main.servers"\
	"(id INTEGER NOT NULL PRIMARY KEY, ip_address TEXT NOT NULL, port INTEGER NOT NULL)"
#define SQL_CREATE_TRIGGER_DEVICES_ON_DEL_SERVER "CREATE TRIGGER IF NOT EXISTS main.on_server_delete "\
	"BEFORE DELETE ON servers BEGIN DELETE FROM devices WHERE "\
	"server_1 = old.id OR server_2 = old.id OR server_3 = old.id; END;"
#define SQL_CREATE_TABLE_DEVICE_TYPES "CREATE TABLE IF NOT EXISTS main.device_types"\
	"(id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL)"

#define SQL_SELECT_DEVICE_TYPE "SELECT t.name FROM main.devices AS d "\
	"INNER JOIN main.device_types AS t ON d.type_id = t.id WHERE d.id = '%llu'"
#define SQL_SELECT_DEVICE_SERVER "SELECT s.ip_address, s.port FROM main.devices AS d "\
	"INNER JOIN main.servers AS s ON d.server_%d = s.id WHERE d.id = '%llu' AND d.server_%d <> 0"

class CConfiguration : private CDataStorage
{
	CConfiguration();
	~CConfiguration();

public:
	static CConfiguration* getInstance();
	static void removeInstance();
	void CheckStorageConsistency(Base::eState& state);

	bool IsDeviceAllowed(Base::eState& state, UInt64 deviceID, Device::eType deviceType);
	Base::eState GetServerForDevice(Device::eTargetServers targetServer, UInt64 deviceID, std::string& ip_address, UInt8& port);

private:
	static CConfiguration* m_pInstance;
};

#endif
